package com.dd.ent.car.service.video;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.dd.ent.car.AppContext;
import com.dd.ent.car.common.bean.video.Video;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.config.UrlConfig;
import com.dd.ent.car.common.vo.VideoVo;
import com.dd.ent.car.service.BaseService;
import com.google.gson.reflect.TypeToken;
import com.pp.ent.base.log.MLog;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.util.Auth;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by aqu-spring on 17/3/16.
 */

public class VideoService extends BaseService {
    public void addVideoToQiuNiu(String videoFile, final String responseUrl, final String progressUrl) {
        String accessKey = "RtVQakqLfN1NBlr2HStgxEb4YM-UuymeNo4ABB_Z";
        String secretKey = "sj0_fTi3pWMawIEkvcKqzWp_vkC79O_fRLNsbWPB";
        String bucket = "dengqu";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        MLog.debug(TAG, "upToken =" + upToken);

        Configuration config = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                .connectTimeout(10) // 链接超时。默认10秒
                .responseTimeout(60) // 服务器响应超时。默认60秒
                //.recorder(recorder)  // recorder分片上传时，已上传片记录器。默认null
                // .recorder(recorder, keyGen)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                //.zone(Zone.zone2) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        // 重用uploadManager。一般地，只需要创建一个uploadManager对象
        UploadManager uploadManager = new UploadManager(config);
        uploadManager.put(videoFile, null, upToken, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                MLog.debug(TAG, "complete key=" + key);
                if (response != null && response.has("hash")) {
                    String playUrl = "http://quydbezgk.hn-bkt.clouddn.com/" + response.optString("hash");
                    MLog.debug(TAG, "complete playUrl=" + playUrl);
                    notifyUI(responseUrl, playUrl);
                }
            }
        }, new UploadOptions(null
                , null, false, new UpProgressHandler() {
            @Override
            public void progress(String key, double percent) {

                MLog.debug(TAG, "key=" + key + ",percent=" + percent);
                notifyUI(progressUrl, key, percent);
            }
        }, new UpCancellationSignal() {
            @Override
            public boolean isCancelled() {
                MLog.debug(TAG, "isCancelled--------------");
                return false;
            }
        }));
    }


    public void commitVideoInfo(Video video, String uid) {
        Map<String, String> params = new HashMap<>();
        params.put("uid", uid);
        params.put("totalTime", "2000");
        params.put("playUrl", video.getPlayUrl());
        params.put("title", video.getTitle());
        params.put("posterUrl", video.getPosterUrl());
        params.put("createTime", String.valueOf(System.currentTimeMillis()));
        post(UrlConfig.COMMIT_VIDEO_INFO, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                notifyUI(UIConfig.ADD_VIDEO_INFO_TO_SERVER_SUCCESS);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
            }
        });
    }

    public void getVideoByUid(String uid) {
        String url = UrlConfig.GET_VIDEO_BY_UID + "uid=" + uid;
        get(url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                notifyUI(UIConfig.GET_VIDEO_INFO_BY_UID_SUCCESS, response == null ? null : response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
                notifyUI(UIConfig.GET_VIDEO_INFO_BY_UID_FAIL);
            }
        });
    }

    public void queryAllFeedVideo() {
        String url = UrlConfig.QUERY_ALL_VIDEO;
        get(url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.debug(TAG, "queryAllFeedVideo response=" + response);
                notifyUI(UIConfig.QUERY_ALL_FEED_VIDEO_SUCCESS, response == null ? null : response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
                notifyUI(UIConfig.QUERY_ALL_FEED_VIDEO_FAIL);
            }
        });
    }

    public void queryVideoByPage(int page, int size) {
        String url = UrlConfig.QUERY_VIDEO_BY_PAGE + "page=" + page + "&size=" + size;
        get(url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.debug(TAG, "queryAllFeedVideo response=" + response);
                notifyUI(UIConfig.QUERY_ALL_FEED_VIDEO_SUCCESS, response == null ? null : response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
                notifyUI(UIConfig.QUERY_ALL_FEED_VIDEO_FAIL);
            }
        });
    }

    public void addLikeToVideo(String videoId, long addCount, String uid) {
        Map<String, String> params = new HashMap<>();
        params.put("videoId", videoId);
        params.put("addCount", String.valueOf(addCount));
        params.put("uid", uid);
        post(UrlConfig.ADD_LIKE_TO_VIDEO, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.info(TAG, "addLikeToVideo onResponse response=" + response);
                notifyUI(UIConfig.ADD_LIKE_TO_VIDEO_SUCCESS);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.info(TAG, "addLikeToVideo onErrorResponse error=" + error);
                MLog.error(TAG, error);
                notifyUI(UIConfig.ADD_LIKE_TO_VIDEO_FAIL);
            }
        });
    }

    public void sumbitPlayCountToVideo(String videoId, long addPlayCount) {
        Map<String, String> params = new HashMap<>();
        params.put("videoId", videoId);
        params.put("addPlayCount", String.valueOf(addPlayCount));
        post(UrlConfig.ADD_VISIT_VIDEO_COUNT, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.info(TAG, "addLikeToVideo onResponse response=" + response);
                VideoVo videoVo = AppContext.createGson().fromJson(response.toString(), new TypeToken<VideoVo>() {
                }.getType());
                if (videoVo != null && videoVo.code == 200) {
                    notifyUI(UIConfig.ADD_PLAY_COUNT_TO_VIDEO_SUCCESS, videoVo);
                } else {
                    notifyUI(UIConfig.ADD_PLAY_COUNT_TO_VIDEO_FAIL);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.info(TAG, "addLikeToVideo onErrorResponse error=" + error);
                MLog.error(TAG, error);
                notifyUI(UIConfig.ADD_PLAY_COUNT_TO_VIDEO_FAIL);
            }
        });
    }


}
